<template>
	<view class="content">
		<view class="title">输入验证码</view>
		<view class="desc">已发送4位数字验证码至 {{ tel }}</view>
		<u-message-input :focus="true" :loading="loading" :value="code" :disabled-keyboard="!canEnter" @finish="codeFinish" @change="codeChange"></u-message-input>
		<view class="again-btn" @click="handleAgain">
			重新获取
			<text v-if="againTime > 0">({{ againTime }}s)</text>
			<u-line color="red"></u-line>
		</view>

		<u-toast ref="uToast" />
	</view>
</template>

<script>
export default {
	data() {
		return {
			loading: false,
			tel: '',
			againTime: 60,
			time: null,
			code: '',
			canEnter: true
		};
	},
	methods: {
		// 重新获取验证码
		async handleAgain() {
			if (this.againTime <= 0) {
				// 重启倒计时
				this.againTime = 60;
				this.resetAgainTime();
				const result = await this.$api.sendMemberCodeSMS({
					mobile: this.tel,
					template: 'login'
				});
				if (result?.resultCode === '200') {
					this.$refs.uToast.show({
						title: result?.resultMsg ?? '"验证码发送成功"',
						type: 'success',
						duration: 3000
					});
				} else {
					// 发送失败 重置倒计时定时器
					this.againTime = 0;
					this._clearInterval();
					this.$refs.uToast.show({
						title: "发送失败",
						type: 'error',
						duration: 3000
					});
				}
			}
		},
		async login(code) {
			const result = await this.$api.login({
				loginCode: this.tel,
				code: code
			});
			if (result?.resultCode === '200') {
				this.$refs.uToast.show({
					title: result?.resultMsg ?? '登录成功',
					type: 'success',
					callback: () => {
						uni.navigateBack({
							delta: 2
						})
						uni.$emit('page-redirect'); // 通讯入口页面继续下次页面操作
					}
				});
			} else {
				// 登录失败
				this.loading = false;
				this.canEnter = true; // 重新允许输入code
				this.$refs.uToast.show({
					title: result?.resultMsg ?? '登录失败',
					type: 'error'
				});
			}
		},
		codeChange(e) {
			console.log(e);
		},
		// 输入验证码完成
		codeFinish(e) {
			const code = e;
			// 设置禁止修改密码
			this.loading = true;
			this.canEnter = false;
			this.login(code);
		},
		resetAgainTime() {
			this.time = setInterval(() => {
				this.againTime--;
				if (this.againTime <= 0) {
					this._clearInterval();
				}
			}, 1000);
		},
		_clearInterval() {
			clearInterval(this.time);
			this.time = null;
		}
	},
	onLoad(options) {
		this.tel = options.phone;
		this.resetAgainTime();
	},
	// 销毁页面时 清除定时器
	onUnload() {
		this._clearInterval();
	}
};
</script>

<style lang="scss">
.content {
	padding: 90rpx 45rpx 30rpx;
}

.title {
	font-size: 55rpx;
	width: 100%;
	margin-bottom: 40rpx;
	font-weight: 500;
}

.desc {
	color: #737373;
	font-size: 30rpx;
	width: 100%;
	text-align: left;
	margin-bottom: 20rpx;
}

.again-btn {
	color: $font-color-red;
	font-size: 28rpx;
	margin-top: 40rpx;
	// text-decoration: underline;
	line-height: 40rpx;
}
</style>
